import sys
import os

# 添加 project/ 目录到 sys.path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

import json
import os
import os.path as osp
import argparse
import cv2
import numpy as np
from PIL import Image
from tqdm import tqdm
import multiprocessing
from tictoc import TicToc
import shutil

def delete_symlink(symlink_path):
    # 检查路径是否存在并且是一个符号链接
    if os.path.exists(symlink_path) and os.path.islink(symlink_path):
        try:
            os.remove(symlink_path)
            print(f"成功删除软链接: {symlink_path}")
        except OSError as e:
            print(f"删除软链接时出错: {e}")
    else:
        print(f"{symlink_path} 不存在或不是一个软链接")

def main_worker(dataset_path, args):
    subdirs = os.listdir(os.path.join(dataset_path, 'camera'))
    normal_links=[]
    for subdir in subdirs:
        if subdir[-6:] == 'normal':
            normal_link = os.path.join(dataset_path, 'camera', subdir)
            assert os.path.islink(normal_link)
            normal_links.append(normal_link)
    for normal_link in normal_links:
            delete_symlink(normal_link)


    print(f'done')


def main(args):
    # 统计耗时
    cost = TicToc("carla2real_before")
    assert os.path.exists(args.data_path)
    frames = os.listdir(args.data_path)
    frames.sort(key=lambda x: x)
    files = []
    for dir in frames:
        if dir[:2] == '__':  # '__'
            dir = os.path.join(args.data_path, dir)
            if os.path.isdir(dir):
                files.append(dir)

    process_size = len(files)
    manager = multiprocessing.Manager()
    if process_size > 1:
        pool = multiprocessing.Pool(process_size)
        counter_list = manager.list()
        for idx in range(process_size):
            pool.apply_async(main_worker, args=(files[idx], args))
        pool.close()
        pool.join()
    else:
        main_worker(files[0], args)

    print("---------------------------------------------------------")
    print("处理完成: {}".format(files))
    cost.toc()
    print("---------------------------------------------------------")


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Configuration Parameters')
    parser.add_argument('--data-path', default="/home/adt/bags/work_space/datasets",
                        help='your data root for kitti')
    args = parser.parse_args()

    main(args)
